package com.dzsw.netty.util;

import com.dzsw.netty.websocket.protocal.CProtocol;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GenericFutureListener;

public class ProtobufUtil {

    public static CProtocol.Message createMessage(CProtocol.Heartbeat heartbeat) {
        CProtocol.Message.Builder builder = CProtocol.Message.newBuilder();
        builder.setType(CProtocol.EnumDataType.HEARTBEAT);
        builder.setHeartbeat(heartbeat);
        return builder.build();
    }

    public static CProtocol.Message createHeartbeat() {
        CProtocol.Heartbeat heartbeat = CProtocol.Heartbeat.newBuilder().build();
        CProtocol.Message.Builder builder = CProtocol.Message.newBuilder();
        builder.setType(CProtocol.EnumDataType.HEARTBEAT);
        builder.setHeartbeat(heartbeat);
        return builder.build();
    }


    public static CProtocol.Message createMessage(CProtocol.Request req) {
        CProtocol.Message.Builder builder = CProtocol.Message.newBuilder();
        builder.setType(CProtocol.EnumDataType.REQUEST);
        builder.setRequest(req);
        return builder.build();
    }

    public static CProtocol.Message createMessage(CProtocol.Response resp) {
        CProtocol.Message.Builder builder = CProtocol.Message.newBuilder();
        builder.setType(CProtocol.EnumDataType.RESPONSE);
        builder.setResponse(resp);
        return builder.build();
    }

    public static void sendBinaryMessage(ChannelHandlerContext ctx, byte[] bytes, boolean needRetain, GenericFutureListener futureListener) {
        ByteBuf bytebuf = ByteBufAllocator.DEFAULT.buffer(bytes.length);
        bytebuf.writeBytes(bytes);if (needRetain) {
            bytebuf.retain();
        }
        ctx.channel().writeAndFlush(new BinaryWebSocketFrame(bytebuf)).addListener(futureListener);
    }

    public static void sendBinaryMessage(ChannelHandlerContext ctx, byte[] bytes, boolean needRetain) {
        ByteBuf bytebuf = ByteBufAllocator.DEFAULT.buffer(bytes.length);
        bytebuf.writeBytes(bytes);if (needRetain) {
            bytebuf.retain();
        }
        ctx.channel().writeAndFlush(new BinaryWebSocketFrame(bytebuf));
    }
}
